<template>
  <div class="app-container" style="padding-left: 0; padding-right: 0">
    <el-card class="box-card" style="margin-bottom: 20px; font-size: 14px">
      <div slot="header" class="clearfix">
        <span class="el-icon-document">历史审批记录</span>
      </div>
      <div class="block" id="appStyle">
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in flowRecordList"
            :key="index"
            :icon="setIcon(item.finishTime)"
            :color="setColor(item.finishTime)"
          >
            <div class="leftStyle">
              <div>
                {{ item.createTime }}
              </div>
            </div>
            <div>
              <p style="font-weight: 700">{{ item.taskName }}</p>
              <div :body-style="{ padding: '10px' }">
                <div
                  v-if="item.assigneeName"
                  style="font-weight: normal; margin-right: 30px"
                >
                  实际办理人： {{ item.assigneeName }}
                  <el-tag type="info" size="mini">{{ item.deptName }} </el-tag>
                </div>

                <div
                  v-if="item.candidate"
                  style="font-weight: normal; margin-right: 30px"
                >
                  候选组/用户办理： {{ item.candidate }}
                </div>
                <div style="font-weight: normal">
                  接收时间：{{ item.createTime }}
                </div>
                <!--                <label style="color: #8a909c; font-weight: normal">{{-->
                <!--                  item.createTime-->
                <!--                  }}</label>-->
                <div
                  v-if="item.finishTime"
                  style="font-weight: normal; display: inline-block"
                >
                  办结时间：{{ item.finishTime }}
                </div>
                <!--                <label style="color: #8a909c; font-weight: normal">{{-->
                <!--                  item.finishTime-->
                <!--                  }}</label>-->
                <label
                  v-if="item.duration"
                  style="
                    margin-left: 30px;
                    font-weight: normal;
                    display: inline-block;
                  "
                  >耗时： </label
                ><label style="color: #8a909c; font-weight: normal">{{
                  item.duration
                }}</label>

                <p v-if="item.comment">
                  <el-tag type="success" v-if="item.comment.type === '1'">
                    {{ item.comment.comment }}
                  </el-tag>
                  <el-tag type="warning" v-if="item.comment.type === '2'">
                    {{ item.comment.comment }}
                  </el-tag>
                  <el-tag type="danger" v-if="item.comment.type === '3'">
                    {{ item.comment.comment }}
                  </el-tag>
                </p>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <el-card
      class="box-card"
      style="margin-bottom: 20px; font-size: 14px"
      v-if="finished == 'false'"
    >
      <div slot="header" class="clearfix">
        <span class="el-icon-document">审批</span>
      </div>
      <el-form
        ref="taskForm"
        :model="taskForm"
        :rules="rules"
        label-width="150px"
        size="mini"
      >
        <el-form-item label="请输入意见" prop="comment">
          <el-input
            style="width: 500px"
            type="textarea"
            rows="4"
            v-model="taskForm.comment"
            placeholder="请输入意见"
          />
        </el-form-item>
        <el-form-item v-if="selectApprover" label="审批人" prop="nextApprover">
          <!-- <LoadPersonSelect :placeholder="'请选择审批人'" @getSelectedParty="getSelectedParty"></LoadPersonSelect> -->
          <el-select
            v-model="taskForm.nextApprover"
            placeholder="请选择审批人"
            filterable
            clearable
          >
            <el-option
              v-for="dict in userIdOptions"
              :key="dict.userId"
              :label="dict.name"
              :value="dict.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-s-promotion"
            type="primary"
            size="mini"
            @click="handleSelectUser"
            >指定后续审批人
          </el-button>

          <el-button
            icon="el-icon-success"
            type="success"
            size="mini"
            @click="handleOver"
            >审批通过
          </el-button>
          <el-button
            icon="el-icon-error"
            type="danger"
            size="mini"
            @click="handleReject"
            >退回申请人
          </el-button>
          <!-- @click="handlereject" -->
          <el-button size="mini" @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog
      title="选择后续审批人"
      :visible.sync="openSelectUser"
      style="overflow-y: auto"
      append-to-body
      width="700px"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="机构" prop="deptId">
          <treeselect
            v-model="userForm.deptId"
            :options="deptOptions"
            :defaultProps="defaultProps"
            :show-count="true"
            @select="changeSelect"
            placeholder="请选择机构"
          />
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="用户编号"
          align="center"
          key="userId"
          prop="userId"
        />
        <el-table-column
          label="用户昵称"
          align="center"
          key="nickName"
          prop="nickName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="部门"
          align="center"
          key="deptName"
          prop="dept.deptName"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getSelectdUser">确 定</el-button>
        <el-button @click="openSelectUser = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { flowRecord } from "@/api/workflow/finished";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getProcessVariables } from "@/api/workflow/definition";
import {
  complete,
  rejectTask,
  returnList,
  returnTask,
  getNextFlowNode,
  delegate,
  nextTask,
  overTask,
  approvalBusi,
} from "@/api/workflow/todo";
import { listWorkflowUser, getPersonDict } from "@/api/system/user";
import LoadPersonSelect from "@/components/LoadPersonSelect";
import { getUserEnum } from "@/api/ehr/enum";

export default {
  name: "approve",
  components: { Treeselect, LoadPersonSelect },
  props: {},
  data() {
    return {
      activeTab: "Approve",
      openSelectUser: false,
      //选择审批人
      selectApprover: false,
      userIdOptions: [],
      // 选中用户名称数组
      userNames: [],
      // 模型xml数据
      xmlData: "",
      taskList: [],
      // 遮罩层
      loading: false,
      flowRecordList: [], // 流程流转数据
      src: null,
      userForm: {},
      userRules: {
        deptId: [
          { required: true, message: "机构不能为空", trigger: "change" },
        ],
      }, // 用户表单校验
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      rules: {}, // 表单校验
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
      },
      // 用户表格数据
      userList: null,
      taskForm: {
        userId: "", //当前用户ID
        partyId: "", //当前用户partyId
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        executionId: "", //当前任务执行编号
        deployId: "", // 流程定义编号
        taskId: "", // 流程任务编号
        procDefId: "", // 流程编号
        businessKey: "", // 业务编号
        taskStatus: "agree", //同意-agree,拒绝-reject
        approveStatus: "", //审批结论：指定审批人 next 、通过 over,拒绝 reject
        assigneeListName: "", //下级审批人
        assigneeList: [],
        nextApprover: "", //后续审批人
      },
      formConf: {}, // 默认表单数据
      formConfOpen: false, // 是否加载默认表单数据
      variables: [], // 流程变量数据
      variablesData: {}, // 流程变量数据
      variableOpen: false, // 是否加载流程变量数据
      finished: false,
      // 表单校验
      rules: {
        nextApprover: [
          { required: true, message: "审批人不能为空", trigger: "change" },
        ],
        comment: [
          { required: true, message: "审批意见不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.taskForm.deployId = this.$route.query && this.$route.query.deployId;
    this.taskForm.taskId = this.$route.query && this.$route.query.taskId;
    this.taskForm.procInsId = this.$route.query && this.$route.query.procInsId;
    this.taskForm.executionId =
      this.$route.query && this.$route.query.executionId;

    this.taskForm.businessKey =
      this.$route.query && this.$route.query.businessKey;
    // 初始化表单
    this.taskForm.procDefId = this.$route.query && this.$route.query.procDefId;

    // 流程任务重获取变量表单
    // if (this.taskForm.taskId) {
    //   this.processVariables(this.taskForm.taskId);
    //   this.taskForm.deployId = null;
    // }
    this.finished = this.$route.query && this.$route.query.finished;
    this.getFlowRecordList(this.taskForm.procInsId, this.taskForm.deployId);

    // 初始下一审批人 userIdOptions
    getUserEnum().then((res) => {
      if (res && res.data) {
        this.userIdOptions = res.data;
      }
    });
  },
  mounted() {},
  computed: {
    userInfo() {
      return this.$store.getters.userInfo; //用户信息
    },
    userPermissions() {
      return this.$store.getters.permissions; //用户权限
    },
  },
  methods: {
    getSelectedParty(e) {
      console.info("打印e组件选择值", e);
      this.taskForm.nextApprover = e;
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 部门下的用户 */
    getList() {
      this.loading = true;
      listWorkflowUser(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 选择机构树后
    changeSelect(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.taskForm.assigneeList = selection.map((item) => item.userId);
      this.userNames = selection.map((item) => item.nickName);
    },
    getSelectdUser() {
      if (this.userNames.length <= 0) {
        this.msgError("请选择用户！");
        return;
      }
      this.taskForm.assigneeListName = this.userNames.join(",");
      this.openSelectUser = false;
    },
    setIcon(val) {
      if (val) {
        return "el-icon-check";
      } else {
        return "el-icon-time";
      }
    },
    setColor(val) {
      if (val) {
        return "#2bc418";
      } else {
        return "#b3bdbb";
      }
    },
    /** 流程流转记录 */
    getFlowRecordList(procInsId, deployId) {
      const params = { procInsId: procInsId, deployId: deployId };
      flowRecord(params)
        .then((res) => {
          this.flowRecordList = res.data.flowList;
          // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
          if (res.data.formData) {
            this.formConf = res.data.formData;
            this.formConfOpen = true;
          }
        })
        .catch((res) => {
          this.goBack();
        });
    },
    fillFormData(form, data) {
      form.fields.forEach((item) => {
        const val = data[item.__vModel__];
        if (val) {
          item.__config__.defaultValue = val;
        }
      });
    },
    /** 获取流程变量内容 */
    // processVariables(taskId) {
    //   if (taskId) {
    //     // 提交流程申请时填写的表单存入了流程变量中后续任务处理时需要展示
    //     getProcessVariables(taskId).then((res) => {
    //       // this.variables = res.data.variables;
    //       this.variablesData = res.data.variables;
    //       this.variableOpen = true;
    //     });
    //   }
    // },
    /** 选择审批人 */
    handleSelectUser() {
      // this.getTreeselect();
      // this.openSelectUser = true;
      this.rules.nextApprover[0].required = true;
      this.selectApprover = true;
      this.taskForm.approveStatus = "next";
      this.taskForm.userId = this.$store.state.user.userId;
      this.taskForm.partyId = this.$store.state.user.partyId;
      this.$refs["taskForm"].validate((valid) => {
        if (
          valid &&
          !this.taskForm.nextApprover == "" &&
          this.taskForm.nextApprover != null
        ) {
          this.loading = true;
          approvalBusi(this.taskForm).then((response) => {
            this.$modal.msgSuccess(response.msg);
            this.loading = false;
            this.goBack();
          });
        }
      });
    },
    /** 结束流程 */
    handleOver() {
      this.taskForm.taskStatus = "over";
      this.taskForm.approveStatus = "over";
      this.selectApprover = false;
      this.rules.nextApprover[0].required = false;
      this.taskForm.userId = this.$store.state.user.userId;
      this.taskForm.partyId = this.$store.state.user.partyId;
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          approvalBusi(this.taskForm).then((response) => {
            this.$modal.msgSuccess(response.msg);
            this.loading = false;
            this.goBack();
          });
        }
      });
    },
    /** 退回申请人 */
    handleReject() {
      this.taskForm.taskStatus = "reject";
      this.taskForm.approveStatus = "reject";
      this.selectApprover = false;
      this.rules.nextApprover[0].required = false;
      this.taskForm.userId = this.$store.state.user.userId;
      this.taskForm.partyId = this.$store.state.user.partyId;
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          // complete(this.taskForm).then((res) => {
          approvalBusi(this.taskForm).then((res) => {
            this.$modal.msgSuccess(res.msg);
            this.loading = false;
            this.goBack();
          });
        }
      });
    },
    handleAssign() {},
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach((item) => {
          let variableData = {};
          variableData.label = item.__config__.label;
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach((val) => {
              array.push(val);
            });
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue;
          }
          variables.push(variableData);
        });
        this.variables = variables;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.leftStyle {
  position: absolute;
  left: -150px;
  top: 1px;
  font-size: 12px;
}

#appStyle {
  position: relative;
  left: 150px;
  width: 70%;
}
</style>
